package com.sea.physical.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sea.physical.entity.Cabinet;
import com.sea.physical.mapper.CabinetMapper;
import com.sea.physical.service.CabinetService;
import com.sea.physical.service.OAuth2ClientService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OAuth2ClientServiceImpl implements OAuth2ClientService {

    private final String BASE_URL = "https://api.eteams.cn/oauth2/authorize";

    private final String TOKEN_URL = "https://api.eteams.cn/oauth2/access_token";

    private final String FILE_URL = "https://api.eteams.cn/api/file/v2/common/upload/base64";

    private final String BACK_URL= "https://api.eteams.cn/api/workflow/core/paService/v1/doForceDrawBack";
    private final String DELETE_URL= "https://api.eteams.cn/api/workflow/core/paService/v1/deleteRequest";

    @Override
    public String getAuthorizationCode(String corpId, String state) throws Exception {
        // 构建请求URL
        String url = String.format("%s?corpid=%s&response_type=code&state=%s",
                BASE_URL, corpId, state);

        // 设置请求头（可根据需要添加）
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        // 发送POST请求（无请求体）
        return doPost(url, headers, null);
    }

    @Override
    public String getAccessToken(String appKey, String appSecret, String code) throws Exception {
        // 构建请求URL
        String url = String.format("%s?app_key=%s&app_secret=%s&grant_type=authorization_code&code=%s",
                TOKEN_URL, appKey, appSecret, code);

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        // 发送POST请求（无请求体）
        return doPost(url, headers, null);
    }

    @Override
    public String getWorkFlow(String body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost("https://api.eteams.cn/api/workflow/core/paService/v1/doCreateRequest");

        // 3. 设置请求头
        httpPost.setHeader("Content-Type", "application/json");


        // 5. 设置请求体
        httpPost.setEntity(new StringEntity(body, "UTF-8"));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 7. 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("Response Status Code: " + statusCode);

        // 8. 获取响应内容
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        if (entity != null) {
            responseBody = EntityUtils.toString(entity);
            System.out.println("Response Body: " + responseBody);
        }
        return responseBody;
    }

    @Override
    public String doPost(String url, Map<String, String> headers, String body) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            if (headers != null) {
                headers.forEach(httpPost::setHeader);
            }

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                return EntityUtils.toString(entity);
            }
            throw new RuntimeException("Empty response");
        }
    }

    @Override
    public String uploadBase64File(String accessToken, String userId, String base64Data, String fileName, long fileSize, long lastModified) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. 构建URL
            String url = FILE_URL + "?access_token=" + accessToken;

            // 2. 创建Multipart请求体
            HttpEntity multipartEntity = MultipartEntityBuilder.create()
                    .setCharset(StandardCharsets.UTF_8)
                    .addTextBody("userid", userId, ContentType.TEXT_PLAIN)
                    .addTextBody("base64", base64Data, ContentType.TEXT_PLAIN)
                    .addTextBody("name", fileName, ContentType.TEXT_PLAIN)
                    .addTextBody("size", String.valueOf(fileSize), ContentType.TEXT_PLAIN)
                    .addTextBody("lastModified", String.valueOf(lastModified), ContentType.TEXT_PLAIN)
                    .build();

            // 3. 创建POST请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(multipartEntity);

            // 4. 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                String fileResponse = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                System.out.println(fileResponse);
                String errCode = JSON.parseObject(fileResponse).getJSONObject("message").getString("errcode");
                if (errCode.equals("0")) {
                    return JSON.parseObject(fileResponse).getJSONObject("data").getString("fileid");
                } else {
                    return null;
                }

            } else {
                return null;
            }

        }
    }

    @Override
    public String doForceDrawBack(String accessToken, String userId, String requestId) throws Exception {
        // 构建请求URL
        String url = String.format("%s?access_token=%s&userid=%s&requestId=%s",
                BACK_URL, accessToken, userId,requestId);

        // 设置请求头（可根据需要添加）
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        // 发送POST请求（无请求体）
        return doPost(url, headers, null);
    }

    @Override
    public String deleteRequest(String accessToken, String userId, String requestId) throws Exception {
        // 构建请求URL
        String url = String.format("%s?access_token=%s&userid=%s&requestId=%s",
                DELETE_URL, accessToken, userId,requestId);

        // 设置请求头（可根据需要添加）
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        // 发送POST请求（无请求体）
        return doPost(url, headers, null);
    }

    @Override
    public String getToken() throws Exception {
        String corpId = "b9f5bd1684453b1ecca952ebc45ab23a";
        String state = "ykjdata2020";


        //获取Code

        String codeResponse = getAuthorizationCode(corpId, state);
        System.out.println("codeResponse: " + codeResponse);


        JSONObject jsonObject = JSON.parseObject(codeResponse);
        String errcode = jsonObject.getString("errcode");

        if (errcode.equals("0")) {
            String code = jsonObject.getString("code");

            if (StringUtils.isNotBlank(code)) {
                String appKey = "7f75d98315b3cfe030ebab30e0b2e81a";
                String appSecret = "9d026803301a23d9475593cc8c2d877d";

                String tokenResponse = getAccessToken(appKey, appSecret, code);
                System.out.println("Access Token Response: " + tokenResponse);


                JSONObject jToken = JSON.parseObject(tokenResponse);
                String eCode = jToken.getString("errcode");
                if (eCode.equals("0")) {
                    String accessToken = jToken.getString("accessToken");

                    System.out.println(accessToken);
                    return accessToken;
                }
            }
            return null;
        }
        return null;
    }
}

